package cn.gjxblog.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.UUID;

/**
 * 作用: 自定义数据源
 * 作者:gjx
 * 版本:V1.0
 */
public class MyRealm extends AuthorizingRealm {
    /**
     * 获取授权信息 角色信息+权限信息
     * 支持三种权限校验方式
     *  1.编程式  subject.hasRole...
     *  2 标签式
     *  3 注解式
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        if("libai".equals(username)){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addRole("root");
            info.addRole("admin");
            info.addRole("user");

            info.addStringPermission("user:add");
            info.addStringPermission("user:query");
            info.addStringPermission("user:remove");
            return info;
        }
        return null;
    }

    /**
     * 获取认证信息方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("**********");
        UsernamePasswordToken usernamePasswordToken=  (UsernamePasswordToken)authenticationToken;

        String username = usernamePasswordToken.getUsername();

        if("libai".equals(username)){
            return new SimpleAuthenticationInfo("libai","3d53b73c485f523ef2fe45f2b8dd3c58",ByteSource.Util.bytes("ABCD"),UUID.randomUUID().toString());
        }

      return null;
    }
}
